import { onMounted, onUnmounted } from 'vue'

/** 按键类型 */
export enum HotkeyType {
  /** 按下 */
  KEYDOWN = 'keydown',

  /** 释放 */
  KEYUP = 'keyup'
}

/** 按键参数 */
export interface HotkeyParams {
  /** 按键事件 */
  e: KeyboardEvent

  /** 按键类型 */
  type: HotkeyType
}

/** 按键数据 */
type KeyboardData = Pick<KeyboardEvent, 'key' | 'code' | 'ctrlKey' | 'metaKey'>

/** 默认按键数据 */
const DEFAULT_PRESSED: KeyboardData = {
  key: '',
  code: '',
  ctrlKey: false,
  metaKey: false
}

/** 全局记录当前按键数据 */
export const GLOBAL_KEYBOARD: KeyboardData = { ...DEFAULT_PRESSED }

/**
 * 快捷键
 */
export default function useHotkey(callback?: (params: HotkeyParams) => void) {
  /** 键盘按下事件 */
  function keydown(e: KeyboardEvent) {
    const { key, code, ctrlKey, metaKey } = e

    Object.assign(GLOBAL_KEYBOARD, { key, code, ctrlKey, metaKey })

    return callback?.({
      e,
      type: HotkeyType.KEYDOWN
    })
  }

  /** 键盘抬起事件 */
  function keyup(e: KeyboardEvent) {
    setTimeout(() => Object.assign(GLOBAL_KEYBOARD, DEFAULT_PRESSED))

    return callback?.({
      e,
      type: HotkeyType.KEYUP
    })
  }

  onMounted(() => {
    document.addEventListener('keydown', keydown)
    document.addEventListener('keyup', keyup)
  })

  onUnmounted(() => {
    document.removeEventListener('keydown', keydown)
    document.removeEventListener('keyup', keyup)
  })
}
